<template>
  <div id="BacStainingOptions" class="panel-detail">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-input type="search" v-model="form.keyvalue" clearable class="vxeInputSearch" @search-click="findList" @clear="findList" @keyup.enter.stop="findList" placeholder="关键字查询"></vxe-input>
        <vxe-button type="text" class="button-blue" @click="findList" icon="vxe-icon-refresh" :loading="loading">刷新</vxe-button>
        <vxe-button type="text" class="button-blue" @click="addBacStainingOptions" icon="vxe-icon-add">新增</vxe-button>
        <vxe-button type="text" class="button-blue" @click="saveBacStainingOptions" icon="vxe-icon-save">保存</vxe-button>
        <vxe-button type="text" class="button-red" @click="deleteBacStainingOptions" icon="vxe-icon-delete">删除</vxe-button>
      </template>
    </vxe-toolbar>
    <div class="tableBox">
      <vxe-table ref="tableRef" border="inner" align="left" class="mytable-scrollbar" resizable :edit-config="{ trigger: 'click', mode: 'cell' }" :loading="loading" height="auto" :data="tableData" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }" @current-change="tableCellClick">
        <vxe-column type='checkbox' width='26'></vxe-column>
        <vxe-column type='seq' title='#' width='30'></vxe-column>
        <vxe-column field='resultCode' title='编号' width='90' :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.resultCode" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field='resultName' title='染色结果' min-width='120' :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.resultName" type="text" @blur="addInputCode(row)"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field='inputCode' title='助记符' min-width='80' :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.inputCode" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field='seq' title='排序码' min-width='60' :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.seq" type="text"></vxe-input>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
/**引入组件区 ==========*/
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import { IsEmpty } from '@/utils/common';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
/**全局变量定义区 ==========*/
let { proxy }: any = getCurrentInstance();
/**左侧表格 */
const loading = ref(false); /**刷新+表格加载*/
const form = reactive({ keyvalue: '' }); /**根据关键字查询*/
const tableRef = ref<VxeTableInstance<RowVO>>(); /**表格ref标记*/
const tableData = reactive([]); /**表格数据*/
let bacStainingOptionsObj: any = reactive({}); /**当前选中的染色结论 */
let currentRow: any = reactive({ id: '', code: '' });
let curIndex = ref(-1);/**保存时记录当前选中索引，更换新完数据后 再次选中改行 */
/**右侧表单*/
const BacStainingOptionsFormRef = ref<InstanceType<typeof BacStainingOptionsForm>>();


defineExpose({
  selectChange /**重置显示文本 */
});

/**方法定义区 =============*/
// onMounted(() => {
//   findList(); /**获取染色结果表格数据*/
// });

/**行切换事件 */
function selectChange(row) {
  Object.assign(bacStainingOptionsObj, row);
  findList();
}

/**获取染色结果表格数据*/
const findList = () => {
  loading.value = true;
  tableData.length = 0; /**放入数据前清空数据*/
  const url = '/bac/staining/options/findStainingOptionsList';
  /**注意此处的数据条数*/
  const a = {
    keyWords: form.keyvalue, stainingConclusionId: !IsEmpty(bacStainingOptionsObj) ? bacStainingOptionsObj.conclusionCode : '123!@#'
  };
  proxy.$http.get(url, { params: a })
    .then(async (res: any) => {
      tableData.push(...res.data);
      loading.value = false;
      if (res && res.data && res.data.length > 0) {
        const newSelRow = curIndex.value >= 0 && curIndex.value <= res.data.length - 1 ? res.data[curIndex.value] : res.data[0];
        tableCellClick({ row: newSelRow });
        const $table = tableRef.value;
        if ($table) {
          currentRow.id = '';
          await $table.setCurrentRow(newSelRow);
        }
      }
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取明细列表数据异常', VxeNotifyType.error);
    });
};

/**新增染色结果*/
async function addBacStainingOptions() {
  tableRef.value?.clearCurrentRow();
  const row = {
    id: '',
    stainingConclusionId: bacStainingOptionsObj.id,
    staConclusionNo: bacStainingOptionsObj.conclusionCode,
    resultCode: '',
    resultName: '',
    inputCode: '',
    seq: tableData.length + 1 + ''
  };
  tableData.push(row);
  await tableRef.value?.setCurrentRow(row);
  await tableRef.value?.setEditCell(row, 'resultCode');
}

/**保存染色结果*/
function saveBacStainingOptions() {
  loading.value = true;
  const row = tableRef.value?.getCurrentRecord();
  curIndex.value = tableRef.value?.getRowIndex(row);
  proxy.$http
    .post('/bac/staining/options/batchSaveStainingOptions', tableData)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        findList();
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
    });
}

/**删除染色结果*/
async function deleteBacStainingOptions() {
  const arr = await tableRef.value?.getCheckboxRecords(true);
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
    return;
  } else {
    proxy
      .$confirm('确定删除选中数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        const url = '/bac/staining/options/batchDeleteStainingOptions';
        const optionsList = await tableRef.value?.getCheckboxRecords(true);
        if (optionsList && optionsList.length > 0) {
          proxy.$http
            .post(url, optionsList)
            .then((res: any) => {
              if (res.status.code === 1) {
                VxeMessage('删除成功', VxeNotifyType.success);
                findList();
                BacStainingOptionsFormRef.value?.clearFormData();
              } else {
                VxeMessage('删除失败', VxeNotifyType.error);
              }
            })
            .catch((err: any) => {
              // VxeMessage('删除染色结果异常', VxeNotifyType.error);
            });
        }
      });
  }
}

/**表格选中当前行*/
function tableCellClick({ row }) {
  Object.assign(currentRow, row);
  proxy.$forceUpdate();
}

// 填写名称 自动生成助记符
function addInputCode(row) {
  row.inputCode = funBdsJsResult('firstPinYinFun', row.resultName);
}

</script>
<style lang="scss" scoped>
#BacStainingOptions {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .splitpanes {
      background-color: $base-white;

      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
    }
  }

  .panel-detail {
    background-color: $base-white;
  }

  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  .tableBox {
    height: calc(100% - 40px);
  }
}
</style>
